package org.openea.eap.module.obpm.util.form.tableexcel;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.openbpm.bus.api.constant.BusColumnCtrlType;
import org.openbpm.bus.api.model.IBusinessColumn;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;














@Service
public class SelectExcellor
  extends BusinessColumnExcellor
{
  BusColumnCtrlType getCtrlType() { return BusColumnCtrlType.SELECT; }



  Object fromExcel(IBusinessColumn column, Object text, JSONObject config) {
    String[] ts = { text.toString() };
    if (getCtrlType() == BusColumnCtrlType.CHECKBOX) {
      ts = text.toString().split(",");
    }
    List<String> ls = new ArrayList<>();
    if (!config.containsKey("options")) {
      return text;
    }
    JSONArray options = config.getJSONArray("options");
    for (String t : ts) {
      boolean exist = false;
      for (int i = 0; i < options.size(); i++) {
        JSONObject op = options.getJSONObject(i);
        if (op.getString("txt").equals(t)) {
          exist = true;
          ls.add(op.getString("key"));
        }
      }
      if (!exist) {
        ls.add(t);
      }
    }
    return StrUtil.join(",", ls.toArray());
  }


  Object toExcel(IBusinessColumn column, Object value, JSONObject config) {
    String[] vs = { value.toString() };
    if (getCtrlType() == BusColumnCtrlType.CHECKBOX) {
      vs = value.toString().split(",");
    }
    List<String> ls = new ArrayList<>();
    if (!config.containsKey("options")) {
      return value;
    }
    JSONArray options = config.getJSONArray("options");
    for (String v : vs) {
      boolean exist = false;
      for (int i = 0; i < options.size(); i++) {
        JSONObject op = options.getJSONObject(i);
        if (op.getString("key").equals(v)) {
          exist = true;
          ls.add(op.getString("txt"));
        }
      }
      if (!exist) {
        ls.add(v);
      }
    }
    return StrUtil.join(",", ls.toArray());
  }
}
